package com.ttxs.tenant.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class TenantDataSourceConfig {
    @Value("${ttxs.tenant.table:'t_tenant_datasource'}")
    private String table;

    @Primary
    @Bean
    public DataSource dataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @DependsOn("dataSource")
    public TenantDataSource dynamicDataSource(DataSource dataSource) {
        Map<Object, Object> dataSourceMap = getAllDataSource(dataSource);
        return new TenantDataSource(dataSource, dataSourceMap);
    }

    private Map<Object, Object> getAllDataSource(DataSource mainDataSource) {
        Map<Object, Object> resultMap = new ConcurrentHashMap<>();
        JdbcTemplate jdbcTemplate = new JdbcTemplate(mainDataSource);
        String sql = "SELECT * FROM " + table;
        jdbcTemplate.query(sql, (RowMapper<DataSourceProperties>) (rs, rowNum) -> {
            DataSourceProperties row = new DataSourceProperties();
            String tenantName = rs.getString("tenant_name");
            row.setUrl(rs.getString("datasource_url"));
            row.setDriverClassName(rs.getString("datasource_driver_class"));
            row.setUsername(rs.getString("datasource_account"));
            row.setPassword(rs.getString("datasource_password"));
            DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
            resultMap.put(tenantName, dataSource);
            return null;
        });
        return resultMap;
    }
}
